package com.srcbox.file.data

import android.app.Activity
import android.content.pm.PackageInfo
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.airbnb.lottie.LottieAnimationView
import com.srcbox.file.R
import com.srcbox.file.adapter.AppList
import com.srcbox.file.util.EggUtil

object Search {
    var isSearch = false
    var v: View? = null
    var packList: ArrayList<PackageInfo?> = ArrayList()
    fun search(context: Activity, v: View, packList: ArrayList<PackageInfo?>, t: String) {
        EggUtil.hideKeyboard(context)
        v.findViewById<LottieAnimationView>(R.id.loaderLottie).visibility =
            View.VISIBLE
        v.findViewById<LottieAnimationView>(R.id.loaderLottie).playAnimation()
        v.findViewById<RecyclerView>(R.id.app_re_list).visibility = View.GONE
        Thread {
            var newPackageList: java.util.ArrayList<PackageInfo?>? =
                ArrayList()
            packList.forEach {
                if (it?.applicationInfo?.loadLabel(context.packageManager)!!.contains(
                        t,
                        true
                    )
                ) {
                    newPackageList?.add(it)
                }
            }
            context.runOnUiThread {
                val jsonO = EggUtil.readSetting(context)
                val isHide = jsonO.getBoolean("os_is_cancel")
                v.findViewById<RecyclerView>(R.id.app_re_list).layoutManager =
                    StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)
                v.findViewById<RecyclerView>(R.id.app_re_list).adapter =
                    AppList(context, newPackageList, isHide)
                val loaderLottie =
                    v.findViewById<LottieAnimationView>(R.id.loaderLottie)
                loaderLottie.visibility = View.GONE
                v.findViewById<RecyclerView>(R.id.app_re_list).visibility =
                    View.VISIBLE
                newPackageList = null
                loaderLottie.cancelAnimation()
                EggUtil.hideKeyboard(context)
                v.findViewById<LottieAnimationView>(R.id.loaderLottie).cancelAnimation()
                if (t != "") {
                    isSearch = true
                    this.v = v
                    this.packList = packList
                } else {
                    isSearch = false
                    this.v = null
                    this.packList = ArrayList()
                }
            }
        }.start()
    }
}